package com.mobartisan.workinglunch.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.mobartisan.workinglunch.R;
import com.mobartisan.workinglunch.SnakeApplication;
import com.mobartisan.workinglunch.bean.globalSetting;
import com.mobartisan.workinglunch.constants.Constants;
import com.mobartisan.workinglunch.ui.adapter.FragmentAdapter;
import com.mobartisan.workinglunch.ui.base.BaseActivity;
import com.mobartisan.workinglunch.ui.fragment.ListFragment;
import com.mobartisan.workinglunch.ui.fragment.PersonFragment;
import com.mobartisan.workinglunch.ui.fragment.RecordFragment;
import com.mobartisan.workinglunch.widget.CheckVersionThread;
import com.roughike.bottombar.BottomBar;
import com.roughike.bottombar.BottomBarTab;
import com.roughike.bottombar.OnTabSelectListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobQuery;
import rx.Subscriber;

import static android.R.id.message;
import static com.mobartisan.workinglunch.constants.Constants.isexist;

public class MainActivity extends BaseActivity implements ViewPager.OnPageChangeListener, OnTabSelectListener {

    private static final String TAG = MainActivity.class.getSimpleName();
    @Bind(R.id.bottomBar)
    BottomBar bottomBar;
    @Bind(R.id.viewpagerId)
    ViewPager viewPager;
    List<Fragment> list;
    FragmentAdapter fragmentAdapter;
    globalSetting setting = null;
    BottomBarTab friend;
    private long firstTime = 0;
    int meswhat = -1;
    public Handler handler  = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    friend = bottomBar.getTabWithId(R.id.tab_friends);
                    friend.setBadgeCount(1);
                    friend.setBadgeHidesWhenActive(false);
                    Constants.isexist=true;
                    break;
                case 1:
                    friend = bottomBar.getTabWithId(R.id.tab_friends);
                    friend.setBadgeCount(1);
                    friend.setBadgeHidesWhenActive(false);
                    Constants.isexist=false;
                    friend.removeBadge();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SnakeApplication.mainActivity = this;
        ButterKnife.bind(this);
        Intent intent = getIntent();
        meswhat=intent.getIntExtra("meswhat",-1);
        Constants.isChangePassword = false;
        this.initView();
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void initView() {
        list = new ArrayList<>();
        RecordFragment recordFragment = new RecordFragment();
        list.add(recordFragment);
        //通过handler调用，这个fragment不能用重新new 对象的方式，需要直接添加单例对象
        list.add(ListFragment.getFragmetntA());
        list.add(PersonFragment.getFragmetntA());
        fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(), list);
        viewPager.setAdapter(fragmentAdapter);
        viewPager.addOnPageChangeListener(this);
        bottomBar.setOnTabSelectListener(this);
        if (!Constants.isCheckout)
            getVersionName();
        if (meswhat==2){
            friend = bottomBar.getTabWithId(R.id.tab_friends);
            friend.setBadgeCount(1);
            friend.setBadgeHidesWhenActive(false);
            Constants.isexist=true;
        }
        if (Constants.isexist){
            friend = bottomBar.getTabWithId(R.id.tab_friends);
            friend.setBadgeCount(1);
            friend.setBadgeHidesWhenActive(false);
            Constants.isexist=true;
        }
    }

    @Override
    public void initData() {

    }

    public String getVersionName() {
        final String[] network_VersionName = new String[1];
        final BmobQuery<globalSetting> bmobQuery = new BmobQuery<globalSetting>();
        //bmobQuery.setLimit(2);
//        bmobQuery.order("createdAt");
//        //先判断是否有缓存
//        boolean isCache = bmobQuery.hasCachedResult(AccountRecord.class);
//        if(isCache){
//            bmobQuery.setCachePolicy(BmobQuery.CachePolicy.CACHE_ELSE_NETWORK);	// 先从缓存取数据，如果没有的话，再从网络取。
//        }else{
//            bmobQuery.setCachePolicy(BmobQuery.CachePolicy.NETWORK_ELSE_CACHE);	// 如果没有缓存的话，则先从网络中取
//        }
//		observable形式
        bmobQuery.findObjectsObservable(globalSetting.class)
                .subscribe(new Subscriber<List<globalSetting>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        loge(e, TAG);
                    }

                    @Override
                    public void onNext(List<globalSetting> persons) {
                        //log("查询成功：共"+persons.size()+"条数据。");
                        //ToastUtils.showShort("查询成功：共" + persons.size() + "条数据。");
                        //给数据重新排序
                        setting = persons.get(0);
                        network_VersionName[0] = setting.getCurrentversion();
                        Constants.isCheckout=true;
                        CheckVersionThread versionThread = new CheckVersionThread(getActivity(), setting,null);
                        versionThread.compareVersionCode();

                    }
                });
//		bmobQuery.findObjects(new FindListener<Person>() {
//
//			@Override
//			public void done(List<Person> object, BmobException e) {
//				if(e==null){
//					toast("查询成功：共"+object.size()+"条数据。");
//					for (Person person : object) {
//						Log.d(TAG, "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ");
//						Log.d(TAG, "ObjectId = "+person.getObjectId());
//						Log.d(TAG, "Name = "+person.getName());
//						Log.d(TAG, "Age = "+person.getAge());
//						Log.d(TAG, "Address = "+person.getAddress());
//						Log.d(TAG, "Gender = "+person.isGender());
//						Log.d(TAG, "CreatedAt = "+person.getCreatedAt());
//						Log.d(TAG, "UpdatedAt = "+person.getUpdatedAt());
//					}
//				}else{
//					loge(e);
//				}
//			}
//		});
        return network_VersionName[0];
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        bottomBar.selectTabAtPosition(position, true);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onTabSelected(@IdRes int tabId) {
        switch (tabId) {
            case R.id.tab_favorites:
                viewPager.setCurrentItem(0);
                break;
            case R.id.tab_nearby:
                viewPager.setCurrentItem(1);
                break;
            case R.id.tab_friends:
                viewPager.setCurrentItem(2);
                if (Constants.isexist){
                    friend = bottomBar.getTabWithId(R.id.tab_friends);
                    friend.setBadgeCount(1);
                    friend.setBadgeHidesWhenActive(false);
                    Constants.isexist=true;
                }
                break;

        }
    }


    @Override
    public void onBackPressed() {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstTime > 2000) {
            Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            firstTime = secondTime;
        } else {
            SnakeApplication.getInstance().exitApp();
        }
    }
}
